package com.acmen.easyapi.executor;

import com.acmen.easyapi.model.Api;
import com.acmen.easyapi.repository.ApiRepository;
import com.acmen.easyapi.util.Md5Util;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
 * @author acmen
 * 接口保存执行器
 */
@Component
public class ApiSaveExe {
    @Resource
    private ApiRepository apiRepository;
    /**
     * 批量创建接口
     *
     * @param apis
     * @return
     */
    public void batchCreate(String appName, List<Api> apis) {
        List<Api> apiList = new ArrayList<>();
        Set apiSet = new HashSet();
        for(Api api : apis){
            String apiId = Md5Util.md5(appName+api.getRequestMethod()+ api.getPath());
            api.setId(apiId);
            api.setAppName(appName);
            Object[] validArgs = {api.getIdx(),api.getModule(),api.getName(),api.getNo(),api.getPermission()
                    ,api.getRequestMethod(), api.getPath(),api.getAuthor(), api.getNote(),api.isCompleted(),
                    api.getReqParamNode(),api.getResParamNode(),api.getRpc()};
            String md5 = Md5Util.md5(JSON.toJSONString(validArgs));
            api.setMd5(md5);
            if(apiSet.contains(api.getId())){
                continue;
            }
            if(!apiRepository.exits(apiId,md5)){
                apiList.add(api);
            }
        }
        List<String> apiIds = apiList.stream().map(api->api.getId()).collect(Collectors.toList());
        apiRepository.batchDelete(apiIds);
        apiRepository.batchCreate(apiList);
    }
}
